<template>
     <el-upload
        class="avatar-uploader"
        action=""
        ref="upload"
        :http-request="handleFileUpload"
        :show-file-list="false"
        :file-list="fileList"
        :before-upload="handleBeforeUpload">
        <el-button size="small" type="success" :loading="loading">上传</el-button>
    </el-upload>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {uploadDoc} from '@/api/data'

const emit = defineEmits(['updateFile'])
let fileList = ref([])
let loading = ref(false)

// succuss 、error 在手动上传模式下不能触发钩子
const handleBeforeUpload = (file)=>{
    loading.value = true
    fileList.value = [file]
    let fileState = false
    let raw = file
    if(raw.type.indexOf('.document')>-1){
        fileState = true
    }else{
        ElMessage.error('请上传doc、docx格式的文件!'); 
        fileState = false
        loading.value = false
        return false
    }
    const isLtSize = raw.size / 1024 / 1024 < 25;
    if (!isLtSize) {
        ElMessage.error('上传的文件大小不能超过 25MB!');
        loading.value = false
        return false
    }
    return fileState&&isLtSize
}
const handleFileUpload = (param)=>{
      const formData = new FormData()
      formData.append('file', param.file)
      uploadDoc(formData).then(res => {
          if(res.code===200){
              ElMessage.success(res.message)
              emit('updateFile')
              loading.value = false
          }
      }).catch(err=>{
      })
}
</script>

<style lang="scss" scoped>

.avatar-uploader{
    :deep(.el-button--success) {
      background-color: rgba(6, 175, 175, 0.2);
      border-color: rgba(6, 175, 175, 0.6);
    }

}

</style>